// pages/search/search.js
const app = getApp();

Page({
  data: {
    searchText: '',
    resources: [],
    filteredResources: [],
    searching: false,
    searchHistory: [],
    hotSearches: ['Photoshop 2025', 'Pr 2025', 'Xmind2025', 'Snipaste', '3ds MAX 2026']
  },
  
  onLoad() {
    console.log('search onLoad');
    // 获取全局资源数据
    this.setData({
      resources: app.globalData.resources,
      searchHistory: app.globalData.searchHistory
    });
  },
  
  // 输入事件
  onInput(e) {
    this.setData({ searchText: e.detail.value });
  },
  
  // 清除搜索内容
  clearSearch() {
    this.setData({ searchText: '' });
  },
  
  // 返回
  goBack() {
    wx.navigateBack();
  },
  
  // 搜索
  search() {
    const keyword = this.data.searchText.trim();
    if (!keyword) return;
    
    // 将关键词转换为小写（或大写）
    const lowerKeyword = keyword.toLowerCase();
    
    // 执行搜索时，将资源字段也转换为小写进行比较
    const filtered = this.data.resources.filter(item => 
      item.title.toLowerCase().includes(lowerKeyword) || 
      item.description.toLowerCase().includes(lowerKeyword) ||
      item.category.toLowerCase().includes(lowerKeyword)
    );
    
    this.setData({
      filteredResources: filtered,
      searching: true
    });
    
    // 保存搜索历史（去重）
    let history = [...this.data.searchHistory];
    if (!history.includes(keyword)) {
      // 限制历史记录数量
      if (history.length >= 10) {
        history.pop();
      }
      history.unshift(keyword);
      this.setData({ searchHistory: history });
      app.globalData.searchHistory = history;
    }
  },
  
  // 使用历史记录搜索
  searchWithHistory(e) {
    const text = e.currentTarget.dataset.text;
    this.setData({ searchText: text });
    this.search();
  },
  
  // 清除历史记录
  clearHistory() {
    this.setData({ searchHistory: [] });
    app.globalData.searchHistory = [];
  },
  
  // 前往详情页
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    console.log('goToDetail(e)');
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },
  
  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url]
    });
  }
})
